import logging
from datetime import datetime

from django.shortcuts import render
from rest_framework.decorators import api_view

from EventMessageWeb.enums.ApiRespCodeEnums import api_response_code
from commonTool.ApiResponse import api_response
from commonTool.class_convert_tool import ClassConvertTool
from commonTool.logs.logs_wrapper import LogUtil
from page.application.const import SESSION_USER_KEY
from page.application.models import User
from page.application.req.loginAO import LoginAO

# Create your views here.
logs = LogUtil()
ResultVO = api_response()

logs = logging.getLogger('tracer')


@api_view(['POST'])
def login(request):
    error_enum = None
    # raise BusinessException(api_response_code.INTERFACE_ASSERTION_FAIL)
    if request.method == 'POST':
        serializer = LoginAO(data=request.data)
        if serializer.is_valid():
            username = serializer.validated_data['username']
            password = serializer.validated_data['password']
            # 校验用户是否存在
            if username and password:
                userObj = User.objects.filter(username=username, del_flag=0)
                if userObj.exists():
                    user = userObj.get()
                    if user.password == password:
                        # 登录成功
                        user_json_str = ClassConvertTool.convertJson(user)
                        if user_json_str:
                            request.session[SESSION_USER_KEY] = user_json_str
                            logs.info("[ 用户登录 ] 登录成功 缓存SESSION = ", request.session.get(SESSION_USER_KEY))
                            if user_json_str:
                                # 更新用户登录时间信息
                                user.last_login_time = datetime.now()
                                user.save()
                                return ResultVO.new_success(data=user_json_str)
                        else:
                            logs.warning("[ 用户登录 ] 登录响应VO异常:", user_json_str)
                            error_enum = api_response_code.API_LOGIN_ERROR
                    else:
                        # 登录失败
                        logs.warning(f"[ 用户登录 ] 用户{username} 密码错误")
                        error_enum = api_response_code.API_LOGIN_PASSWORD_ERROR
                else:
                    logs.warning(f"[ 用户登录 ] 用户不存在,data:", username, password)
                    # 用户不存在
                    error_enum = api_response_code.API_LOGIN_USER_NOT_EXIST
            else:
                error_enum = api_response_code.API_LOGIN_ERROR

        else:
            # 必填项
            error_enum = api_response_code.CUSTOM_MUST_INPUT

    return ResultVO.new_fail(enum=error_enum)


def login_page(request):
    return render(request, 'login.html')


def logout(request):
    request.session.flush()
    return ResultVO.new_success()


def __get_form_data(**kwargs):
    return_data = {}
    for key, value in kwargs.items():
        if value:
            return_data[key] = value
    return return_data
